import socketAPI from "@/api/socket/socket";
import deviceAPI from "@/api/device/device";
export default {
  name: "ItemController",
  props: {
    value: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      commanding: false,
      device: {},
    };
  },
  computed: {
    buttonType() {
      return this.buttonTypeByDevice(this.value);
    },
  },
  watch: {
    value(nv, ov) {
      this.setValue(nv);
    },
  },
  created() {
    this.setValue(this.value);
    socketAPI.addHandle(this.websocketReceive);
  },
  beforeDestory() {
    socketAPI.removeHandle(this.websocketReceive);
  },
  methods: {
    setValue(value) {
      if (!value) {
        return;
      }
      this.device = Object.assign({}, value);
      this.deviceLoaded(this.device);
    },
    buttonTypeByDevice(device) {
      return device && device.online ? "primary" : "";
    },
    setDevice(item) {
      console.warn("not rewrite setItemDevice method");
      console.warn(item);
    },
    clearData() {},
    deviceLoaded(device) {
      this.clearData();
      if (!device.array) {
        socketAPI.subscribe(device.code);
        this.setDevice(device);
        return;
      }
      for (var i = 0; i < device.array.length; i++) {
        socketAPI.subscribe(device.array[i].code);
        this.setDevice(device.array[i]);
      }
    },
    websocketReceive(data) {
      if (this.device.type !== data.type) {
        return;
      }
      if (data.code !== this.device.code) {
        return;
      }
      this.device = Object.assign({}, this.device, data);
      this.setDevice(this.device);
      return;
    },
    doCommand(code, command, content, action) {
      this.commanding = true;
      deviceAPI
        .command({
          code,
          command,
          content,
          action,
        })
        .then(() => {
          this.commanding = false;
        });
    },
    deviceCommand(command, content, action) {
      this.doCommand(this.device.code, command, content, action);
    },
  },
};
